package fm.dongman.animefm.view.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import org.jetbrains.annotations.NotNull;

import fm.dongman.animefm.R;
import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.contract.ArticleInfoContract;
import fm.dongman.animefm.view.util.SystemHelper;
import fm.dongman.animefm.view.util.ToastHelper;
import fm.dongman.modellib.StaticArea.Injection;
import fm.dongman.modellib.model.ArticleModel;
import fm.dongman.presenterlib.presenter.ArticleInfoPresenter;
import fm.dongman.presenterlib.util.ValidateHelper;


public class WebViewFragment extends Fragment implements View.OnClickListener, ArticleInfoContract.IArticleInfoView {
    private static final String ARG_URL = "http_url";
    private static final String ARG_READ_MODE = "read_mode";

    private ArticleInfoContract.IArticleInfoPresenter mPresenter; // 全局数据控制器
    private String mUrlAddr;
    private Toolbar mToolbar;
    private ImageButton mIbBack;
    private ImageButton mIbMore;
    private ImageButton mIbRefresh;
    private WebView mWebView;
    private ProgressBar mProgressBar;
    private TextView mTvWebTitle;
    private boolean mIsReadMode = false;

    public WebViewFragment() {
        // Required empty public constructor
    }

    public static WebViewFragment newInstance(String url, boolean readMode) {
        WebViewFragment fragment = new WebViewFragment();
        Bundle args = new Bundle();
        args.putString(ARG_URL, url);
        args.putBoolean(ARG_READ_MODE, readMode);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            // 检测是否为文章id
            if (!ValidateHelper.INSTANCE.isNumber(getArguments().getString(ARG_URL)))
                mUrlAddr = getArguments().getString(ARG_URL);
            mIsReadMode = getArguments().getBoolean(ARG_READ_MODE, false);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View layoutView = View.inflate(getActivity(), R.layout.fragment_web_view, null);
        new ArticleInfoPresenter(this, Injection.provideArticleInfoRepository());
        initComponents(layoutView);
        return layoutView;
    }

    @Override
    public void onResume() {
        super.onResume();
        mWebView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mWebView.onPause();
    }

    /**
     * 初始化所有控件
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initComponents(View layout) {
        mToolbar = (Toolbar) layout.findViewById(R.id.mTbWebViewToolBar);
        mToolbar.setPadding(0, SystemHelper.INSTANCE.getStatusBarHeight(getActivity()), 0, 0);
        mProgressBar = (ProgressBar) layout.findViewById(R.id.mTbWebViewProgress);
        mProgressBar.setMax(100);
        mIbBack = (ImageButton) layout.findViewById(R.id.mIbWebViewClose);
        mIbBack.setOnClickListener(this);
        mTvWebTitle = (TextView) layout.findViewById(R.id.mTbWebViewTitle);
        mIbMore = (ImageButton) layout.findViewById(R.id.mIbWebViewMore);
        mIbMore.setOnClickListener(this);
        mIbRefresh = (ImageButton) layout.findViewById(R.id.mIbWebViewRefresh);
        mIbRefresh.setOnClickListener(this);

        mWebView = (WebView) layout.findViewById(R.id.mTbWebViewBrowser);
        mWebView.setWebViewClient(new WebViewClient());
        mWebView.getSettings().setJavaScriptEnabled(true);

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (mProgressBar.getProgress() < 100) {
                    mProgressBar.setVisibility(View.VISIBLE);
                } else {
                    mProgressBar.setVisibility(View.GONE);
                }
                mProgressBar.setProgress(newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (title != null)
                    mTvWebTitle.setText(title);
            }
        });

        mWebView.addJavascriptInterface(new Object() {
            @JavascriptInterface
            public void openInSystemBrowser(String url) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                getActivity().startActivity(intent);
            }
        }, "android");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        //如果是阅读模式，隐藏多余功能，调整部分布局
        if (mIsReadMode) {
            mIbMore.setVisibility(View.GONE);
            mIbRefresh.setVisibility(View.GONE);
            Toolbar.LayoutParams params = (Toolbar.LayoutParams) mTvWebTitle.getLayoutParams();
            params.rightMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getActivity().getResources().getDisplayMetrics());
            mTvWebTitle.setLayoutParams(params);
        }

        if (mUrlAddr == null) {
            mPresenter.getArticleInfo(validateStr(getArguments().getString(ARG_URL)));
            return;
        }
        mWebView.loadUrl(mUrlAddr);
    }

    @NotNull
    private String validateStr(@Nullable String str) {
        if (str == null)
            return "";
        return str;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.mIbWebViewClose:
                getActivity().finish();
                break;

            case R.id.mIbWebViewRefresh:
                mWebView.reload();
                break;

            case R.id.mIbWebViewMore:
                final BottomSheetDialog dialog = new BottomSheetDialog(getActivity(), R.style.Theme_Design_BottomSheetDialog_MyBottomSheet);
                View view = View.inflate(getActivity(), R.layout.dialog_webview_more, null);
                TextView openInWeb = (TextView) view.findViewById(R.id.mTvWebDialogOpenInBrowser);
                TextView copyLink = (TextView) view.findViewById(R.id.mTvWebDialogCopyLink);
                TextView cancel = (TextView) view.findViewById(R.id.mTvWebDialogCancel);

                openInWeb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent i = new Intent(Intent.ACTION_VIEW);
                        i.setData(Uri.parse(mUrlAddr));
                        getActivity().startActivity(i);
                        dialog.dismiss();
                    }
                });
                copyLink.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ClipboardManager clipboardManager = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                        clipboardManager.setPrimaryClip(ClipData.newPlainText("url", mUrlAddr));
                        ToastHelper.getInstance(getActivity()).showSucceed("复制成功");
                        dialog.dismiss();
                    }
                });

                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });

                dialog.setContentView(view);
                dialog.show();
                break;
        }
    }

    public boolean isWebViewCanGoBack() {
        return mWebView.canGoBack();
    }

    public void webViewGoBack() {
        mWebView.goBack();
    }

    @Override
    public void showArticleInfo(@NotNull IModel.IArticleModel articleInfo) {
        mUrlAddr = ((ArticleModel) articleInfo).getArticleURL();
        mWebView.loadUrl(mUrlAddr);
    }

    @Override
    public void setPresenter(ArticleInfoContract.IArticleInfoPresenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public boolean isActive() {
        return isAdded();
    }

    @NotNull
    @Override
    public Context getViewContext() {
        return getActivity();
    }

    @Override
    public void showNoNetwork() {

    }

    @Override
    public void showRefreshFailed() {

    }
}
